<template>
<div class="containerWrap">
  <el-container class="container">
    <el-aside class="appTree" width="200px">
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main class="rightMain">
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              部门名称：
              <el-select filterable  v-model="queryData.deptId" placeholder="部门名称" size="small">
                <el-option v-for="item in deptOption"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name" ></el-option>
              </el-select>
            </div>
            <div>
              联系人：<el-input size="small" placeholder="请输入联系人" v-model="queryData.firstResponsibilityId" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              联系电话：<el-input size="small" placeholder="请输入联系电话" v-model="queryData.firstResponsibilityPhone" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="tableMain">
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"/>
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  :close-on-click-modal="false" :before-close="close" class="dialog_style">
          <div class="formWrapper">
            <el-form class="formMain" :model="formData"
                    :rules="rules"
                    ref="formData"
                    label-width="95px"
                    size="small">
              <el-divider content-position="left">基本信息</el-divider>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="账号：" prop="name">
                    <el-input v-model="formData.account" placeholder="账号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="姓名：" prop="name">
                    <el-input v-model="formData.name" placeholder="姓名"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系方式：" prop="phone">
                    <el-input v-model="formData.phone" placeholder="联系方式"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件代码：" prop="idCardCode">
                    <el-select filterable style="width:100%" v-model="formData.idCardCode" placeholder="证件代码：">
                      <el-option v-for="item in cardOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件号码：" label-width="100px" prop="idCardNumber">
                    <el-input v-model="formData.idCardNumber" placeholder="证件号码"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属部门：" prop="deptId">
                     <el-select filterable style="width:100%" v-model="formData.deptId" placeholder="所属部门">
                      <el-option v-for="item in deptOption"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="角色：">
                    <el-select v-model="formData.roleIdList" style="width:100%" clearable filterable multiple placeholder="请选择角色">
                      <el-option v-for="item in allRole" :key="item.id" :value="item.id" :label="item.roleName"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别：" prop="sex">
                     <el-select filterable style="width:100%" v-model="formData.sex" placeholder="性别">
                      <el-option v-for="item in genderOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用户类型：" prop="type">
                     <el-select filterable style="width:100%" v-model="formData.type" placeholder="用户类型">
                      <el-option v-for="item in typeOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="律师编号："  prop="lawyerCode">
                    <el-input v-model="formData.lawyerCode" placeholder="律师编号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="证件扫描件：" class="spcialLabel4">
                    <app-file ref="appUpload"
                                v-model="formData.certificateFile"></app-file>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生日：" prop="birthday">
                    <el-date-picker
                      style="width:100%"
                      v-model="formData.birthday"
                      value-format="timestamp"
                      format="yyyy 年 MM 月 dd 日"
                      placeholder="选择日期时间"
                      :picker-options="dataPickerBeforeTodayOptions">
                      </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="民族：" prop="nation">
                    <el-select filterable style="width:100%" v-model="formData.nation" placeholder="民族">
                      <el-option v-for="item in nationOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="政治面貌：" prop="politicsStatus">
                     <el-select filterable style="width:100%" v-model="formData.politicsStatus" placeholder="政治面貌">
                      <el-option v-for="item in politicalStatusOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="学历：" prop="education">
                     <el-select filterable style="width:100%" v-model="formData.education" placeholder="学历">
                      <el-option v-for="item in educationOption"
                        :key="item.id"
                        :value="item.value"
                        :label="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                 <el-col :span="12">
                  <el-form-item label="毕业学校：" prop="school">
                     <el-input v-model="formData.school" placeholder="毕业学校"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="专业：" prop="major">
                     <el-input v-model="formData.major" placeholder="专业"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱：" prop="email">
                     <el-input v-model="formData.email" placeholder="邮箱"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="QQ：" prop="qq">
                     <el-input v-model="formData.qq" placeholder="QQ"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="地址：" prop="address">
                     <el-input v-model="formData.address" placeholder="地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="启用：" prop="disableStatus">
                    <el-select filterable style="width:100%" v-model="formData.disableStatus" placeholder="启用">
                      <el-option :key="1" :value="1" label="是"></el-option>
                      <el-option :key="0" :value="0" label="否"></el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="照片" class="spcialLabel4">
                    <app-upload ref="appUpload"
                                v-model="formData.photo"></app-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel('formData')">取 消</el-button>
              <el-button size="small" type="primary" :disabled="showOnly" @click="save('formData')">提 交</el-button>
            </div>
          </div>
        </el-dialog>
        <el-dialog class="dialog-body-mini dialog-body-map" :visible.sync="showMap" title="地图标记" width="70%" top="8vh" :before-close="mapCancel">
          <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget" :row-id="currentSelectedRowId"></edit-map>
        </el-dialog>
      </el-container>
    </el-main>
  </el-container>
</div>
</template>

<script>
import AppUpload from '@/components/AppAvatarUpload'
import AppFile from '@/components/AppLoadFileSingle'
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import { createUser, findUser, updateUser, deleteUser, getUser, getAllRole } from '@/http/setApi'
import { findUnitTree, findDeptList } from '@/http/AppApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
// import {validateIdefer, validatePhone} from '@/utils/validate'
export default {
  data () {
    return {
      active: 1,
      mapMode: 'full',
      dialogTitle: '新增用户',
      currentSelectedRowId: '',
      showMap: false,
      showOnly: false,
      dialogFormVisible: false,
      allRole: [],
      treeData: [],
      treeOption: [],
      deptOption: [],
      cardOption: [],
      typeOption: [],
      nationOption: [],
      genderOption: [],
      educationOption: [],
      currentSelectedData: [],
      politicalStatusOption: [],
      formData: {},
      pageData: {},
      queryData: {},
      mapTarget: {},
      gridIdProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      tableColumns: [
        { label: '账号', prop: 'account' },
        { label: '姓名', prop: 'name' },
        { label: '联系方式', prop: 'phone' },
        { label: '身份证号码', prop: 'idCardNumber' },
        { label: '部门名称', prop: 'deptId', formatter: this.deptFormatter },
        { label: '最后登录时间', prop: 'lastLoginTime', formatter: this.timeFormatter },
        { label: '启用状态', prop: 'disableStatus', formatter: this.statusFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          // return time.getTime() > Date.now()
        }
      },
      rules: {
        account: [{
          required: true,
          message: '填写账号',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '填写姓名',
          trigger: 'blur'
        }],
        deptId: [{
          required: true,
          message: '请选择部门',
          trigger: 'change'
        }],
        idCardCode: [{
          required: false,
          message: '请选择证件类型',
          trigger: 'change'
        }],
        idCardNumber: [{
          required: false,
          message: '请填写身份证',
          trigger: 'blur'
        }],
        phone: [{
          required: false,
          message: '请填写手机号',
          trigger: 'blur'
        }],
        disableStatus: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }]
      }
    }
  },
  mounted () {
    this.findDeptList()
    this.getTableData()
    this.getUnitTree()
    this.getAllRole()
    this.genderOption = getDictDataOption('性别')
    this.cardOption = getDictDataOption('证件代码')
    this.nationOption = getDictDataOption('民族')
    this.politicalStatusOption = getDictDataOption('政治面貌')
    this.educationOption = getDictDataOption('学历')
    this.typeOption = getDictDataOption('人员类型')
  },
  components: {AppTree, BtnGroup, AppTable, EditMap, AppUpload, AppFile},
  methods: {
    deptFormatter (row, column) {
      let options = this.deptOption
      let deptName = ''
      for (let i = 0; i < options.length; i++) {
        const element = options[i]
        if (element.id === row.deptId) {
          deptName = element.name
        }
      }
      return deptName
    },
    timeFormatter (row) {
      if (row && row.lastLoginTime) {
        return this.$moment(row.lastLoginTime).format('YYYY-MM-DD HH:mm')
      }
    },
    statusFormatter (row) {
      return row.disableStatus === 1 ? '启用' : '未启用'
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.formData.id) {
            updateUser(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          } else {
            createUser(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.cancel(formName)
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteUser(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({type: 'success', message: '删除成功'})
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    getTableData () {
      let param = this.queryData
      findUser(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getUnitTree () {
      findUnitTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.treeData = this.treeOption = data
        }
      })
    },
    getAllRole () {
      getAllRole().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.allRole = data
        }
      })
    },
    findDeptList (id) {
      let param = {'unitId': id}
      findDeptList(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.deptOption = data
        }
      })
    },
    treeClickHandle (data) {
      console.log(data)
      this.queryData = {}
      this.findDeptList(data.id)
    },
    btnClickCallback (callbackData) {
      this.dialogFormVisible = true
      this.showOnly = callbackData.showOnly
      this.dialogTitle = callbackData.dialogTitle
      if (callbackData.btnType === 'post') {
        this.formData = {}
      } else if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        let data = callbackData.rows[0]
        this.getUser(data.id)
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    getUser (id) {
      getUser(id).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.formData = data
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    close (type) {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    next (value) {
      if (value === 10) {
        if (!this.formData.id) {
          this.$message({type: 'warning', message: '请先提交信息'})
        } else {
          this.active = value
        }
      } else {
        this.active = value
      }
      if (value === 4) {
        console.log(111)
        this.memberData = {'offset': 0,
          'limit': 10,
          'total': 4,
          'sortField': 'lastUpdate',
          'sortOrder': 'DESC',
          'items': [
            {
              address: null,
              allArea: '0',
              allGridId: '0,589127173513142273,589127390555791362,589127391973466113,589127415784529921,589127420092080130',
              buildingNum: 19,
              businessArea: 0,
              communityPic: '',
              createBy: '591326584817201154',
              createTime: 1533258196,
              displayOrder: 0,
              familyNum: 539,
              familyTotal: 792,
              gridId: '589127420092080130',
              houseArea: 0,
              id: '589376095049453570',
              introduction: '',
              latitude: null,
              longitude: null,
              mapMarkStatus: '已标记',
              name: '平电一号院',
              populationNum: 578,
              propertyArea: 0,
              propertyCompany: '',
              propertyPhone: '',
              propertyPrincipal: '',
              status: 1,
              updateBy: '-1',
              updateTime: 1570757922447
            }
          ]}
      }
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        if (appMapInfo.target.targetId) {
          let mapLocation = {}
          if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
            let length = appMapInfo.poly.length
            this.saveMapLocationInfoByArray(0, length, appMapInfo)
          } else {
            mapLocation = this.appMapInfo2MapLocation(appMapInfo)
            this.saveMapLocationInfo(mapLocation)
          }
        } else {
          this.showOnly = false
          this.showMap = false
          this.$set(this.formData, 'latitude', appMapInfo.lnglat.lat)
          this.$set(this.formData, 'longitude', appMapInfo.lnglat.lng)
        }
      }
      return ''
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
</style>
